package chapter26;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/28 14:36
 */
public class FunctionTest {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(new Student[]{
                new Student("zhangsan", 87.2),
                new Student("li", 87.2),
                new Student("wangwu", 97.4)});

        List<Student> result = filter(students, t -> t.getScore() > 90);
        System.out.println(result);

        List<String> nameList = map(students, t -> t.getName());
        System.out.println(nameList);

        toUpperCase(students, t -> {
            t.setName(t.getName().toUpperCase());
        });
        System.out.println(students);

        students.sort(Comparator.comparingDouble(Student::getScore)
                .reversed()
                .thenComparing(Student::getName));
        System.out.println(students);

        long above90Count = students.stream().filter(student -> student.getScore() >= 90).count();
        System.out.println(above90Count);

        boolean allPass = students.stream().allMatch(student -> student.getScore() >= 60);
        System.out.println(allPass);

        Student[] above90Arr = students.stream().filter(t -> t.getScore() > 90).toArray(Student[]::new);
        System.out.println(Arrays.toString(above90Arr));

    }

    public static <E> List<E> filter(List<E> list, Predicate<E> predicate) {
        List<E> retList = new ArrayList<>();
        for (E e : list) {
            if (predicate.test(e)) {
                retList.add(e);
            }
        }
        return retList;
    }

    public static <T, R> List<R> map(List<T> list, Function<T, R> mapper) {
        List<R> result = new ArrayList<>();
        for (T t : list) {
            R r = mapper.apply(t);
            result.add(r);
        }
        return result;
    }

    public static <T> void toUpperCase(List<T> students, Consumer<T> consumer) {
        for (T student : students) {
            consumer.accept(student);
        }
    }
}
